package org.swift.mashup.engine.model;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.axis2.AxisFault;
import org.apache.log4j.Logger;
import org.swift.commons.client.Call;
import org.swift.commons.client.RestCall;
import org.swift.mashup.engine.cache.CacheKey;
import org.swift.mashup.engine.cache.ComplexCacheKey;
import org.swift.mashup.engine.cache.ServiceCacheManager;

public class RemoteFrom extends BaseFrom {
	private static final Logger logger = Logger.getLogger(RemoteFrom.class);
	private static final int DEFAULT_CACHE_DURATION = 30;
	
	private final ServiceCacheManager cache;
	private final Call call;
	private final int cacheDuration;

	public RemoteFrom(String source, Call call) {
		this(source, call, null, DEFAULT_CACHE_DURATION);
	}

	public RemoteFrom(String source, Call call, int cacheDuration) {
		this(source, call, null, cacheDuration);
	}
	
	public RemoteFrom(String source, Call call, ServiceCacheManager cache) {
		this(source, call, cache, DEFAULT_CACHE_DURATION);
	}

	public RemoteFrom(String source, Call call, ServiceCacheManager cache, int cacheDuration) {
		super(source);
		this.call = call;
		this.cacheDuration = cacheDuration;
		if(cacheDuration != 0) {
			this.cache = cache == null ? getCacheManager() : cache;
		}
		else {
			this.cache = null;
		}
		if(cacheDuration != 0 && cache == null) {
			logger.warn("No valid cache instance for source " + source + "; not caching");
		}
	}

	private static ServiceCacheManager getCacheManager() {
		ServiceCacheManager cache = null;
		try {
			cache = ServiceCacheManager.getInstance();
		}
		catch(Exception e) {
			logger.error("Couldn't get ServiceCacheManager instance", e);
		}
		return cache;
	}

	public Object getValue(Map<String, ? extends Object> map,
			Map<String, ? extends Object> restmap) {

		return getValue(map, restmap, null);
	}
	
	public Object getValue(Map<String, ? extends Object> map,
			Map<String, ? extends Object> restmap,
			Map<String, String> headermap) {
		InputStream results = null;
		CacheKey key = null;
		if(isCacheable()){
			logger.debug("trying to retrieve from cache...");
			key = createCacheKey(map, restmap, headermap);
			logger.debug("RemoteFrom cache key [" + key + "]");
			results = cache.getAsInputStream(key);
			if (results != null) {
				logger.debug("results found in cache.");
				return results;
			}
		}
		try {
			if(call instanceof RestCall){
				if(logger.isDebugEnabled()) {
					logger.debug("Sending request to " + this.call.getURL() + " with parameters " 
						+ map.toString() + " and rest parameters " + restmap.toString()
						+ (headermap == null ? "" : " and headers " + headermap.toString()));
				}
				if ( headermap != null ) {
					((RestCall)call).setCustomHeaders(headermap);
				}
				results = ((RestCall)call).sendRecieve(map, restmap);
			}else{
				logger.debug("Sending request to " + this.call.getURL() + " with parameters " + map.toString());
				results = call.sendRecieve(map);
			}
		} catch (AxisFault e) {
			throw new RuntimeException(e);
		}
		if(isCacheable()){
			logger.debug("caching results...");
			results = cache.putInputStream(key, results,this.getCacheDuration());
		}
		return results;
	}

	protected CacheKey createCacheKey(
			Map<String, ? extends Object> map,
	        Map<String, ? extends Object> restmap,
	        Map<String, String> headermap) {

		Map valuesRelevantToCaching = new HashMap();

		valuesRelevantToCaching.putAll(map);
		valuesRelevantToCaching.putAll(restmap);
		valuesRelevantToCaching.putAll(headermap);

		return new ComplexCacheKey(call, valuesRelevantToCaching, new ArrayList<String>());
	}

	public int getCacheDuration() {
		return cacheDuration;
	}
	
	public boolean isCacheable(){		
		return ((cacheDuration != 0) && (cache != null));
	}

}
